#include "fileutil.h"

//列出所有的.yml文件
void FSUtil::ListAllFile(const std::string& path, const std::string& suffix, std::vector<std::string>& files)
{
    if(access(path.c_str(), F_OK))
    {
        return;
    }
    DIR* dir = opendir(path.c_str());
    if(dir == nullptr)
    {
        return;
    }
    struct dirent* dp = nullptr;
    while((dp = readdir(dir)) != nullptr)
    {
        if(dp->d_type == DT_DIR)
        {
            if(!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
            {
                continue;
            }
            ListAllFile(path + "/" + dp->d_name, suffix, files);
        }
        else if(dp->d_type == DT_REG)
        {
            std::string filename(dp->d_name);
            if(suffix.empty())
            {
                files.push_back(path + "/" + filename);
            }
            else
            {
                if(filename.size() < suffix.size())
                {
                    continue;
                }
                if(filename.substr(filename.length() - suffix.size()) == suffix)
                {
                    files.push_back(path + "/" + filename);
                }
            }
        }
    }
}

//得到文件的属性状态
static int __lstat(const char* file, struct stat* st = nullptr)
{
    struct stat lst;
    int ret = lstat(file, & lst);
    if(st)
    {
        *st = lst;
    }
    return ret;
}

//创建文件夹
static int __mkdir(const char* dirname)
{
    if(access(dirname, F_OK) == 0)
    {
        return 0;
    }
    return mkdir(dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}

bool FSUtil::Mkdir(const std::string& dirname)
{
    //判断文件加是否存在
    if(__lstat(dirname.c_str()) == 0)
    {
        return true;
    }
    //得到路径
    char* path = strdup(dirname.c_str());
    //
    char* ptr = strchr(path + 1, '/');
    do
    {
        for(; ptr; *ptr = '/', ptr = strchr(ptr + 1, '/'))
        {
            *ptr = '\0';
            if(__mkdir(path) != 0)
            {
                break;
            }
        }
        //
        if(ptr != nullptr)
        {
            break;
        }
        //创建文件夹
        else if(__mkdir(path) != 0)
        {
            break;
        }
        free(path);
        return true;
    } while (0);
    free(path);
    return false;
}